import React, { useState, useCallback, useRef, useMemo } from "react";
import Taro from "@tarojs/taro";
import { View, Text, Image, Button } from "@tarojs/components";
import { observer } from "mobx-react";
import i18n from "i18n-js";
import { DynamicColors, GStyleSheet } from "@/utils/DarkMode";
import { wechatLoginByCode } from "@/services/aepApi";
import { useLanguageStore } from "@/hooks";
import { wechatLogin } from "@/utils/loginStatus";
import { getAppInfo } from "@/config/template";
import PageContainer from "@/components/PageContainer";
import Toast from "@/utils/Toast";
import { goLicense } from '@/utils';
import CheckBox from "@/components/CheckBox";

const dstyle = GStyleSheet.create({
  icon: {
    width: "162rpx",
    height: "162rpx",
    borderRadius: 12,
    marginBottom: 10,
  },
  title: {
    fontSize: 16,
    marginTop: 12,
  },
  button: {
    boxSizing: "border-box",
    margin: "0 34px",
    borderRadius: 4,
    height: 48,
    backgroundColor: "#1ABD6B",
    color: "#fff",
  },
  license: {
    display: "flex",
    fontSize: 14,
    alignItems: "center",
    gap: 8,
    color: "#797979",
    marginTop: 15,
  },
  checkbox: { width: 12, height: 12, },
  licenseWrap: {
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    gap: 8,
  },
  link: { color: "#4888FA" },
});

const agreeButtonId = 'agreeButtonId'

const NewLogin: React.FC = () => {
  const styles = dstyle.useDynamicStyle();
  const [isSelectLicense, setIsSelectLicense] = useState(false);
  const language = useLanguageStore();
  const appInfo = useMemo(() => {
    return getAppInfo(language.key);
  }, [language.key]);

  const resolveRef = useRef()

  // const [code, setCode] = useState<string | undefined>(undefined);

  // const getCode = useCallback(() => {
  //   Taro.login({
  //     success: (res) => {
  //       setCode(res.code);
  //     },
  //   });
  // }, []);

  // useEffect(() => {
  //   getCode();
  // }, [getCode]);

  const bindAgreePrivacyAuthorization = useCallback((resolve, eventInfo) => {
    console.log('bindAgreePrivacyAuthorization', eventInfo);
    resolveRef.current = resolve
  }, [])

  const login = useCallback(async ({ }) => {
    console.log('login');
    Toast.loading("");
    const { errMsg, code } = await Taro.login();
    if (errMsg.includes('ok')) {
      const res = await wechatLoginByCode({ code });
      Toast.hideLoading();
      if (res.success) {
        Taro.navigateBack();
        setTimeout(() => {
          wechatLogin({...res.data, ...res.user});
        }, 200);
      } else {
        // 失败的话，刷新下code
        Toast.error(res.message);
        // getCode();
      }
    } else {
      Toast.error(errMsg);
      }
  }, []);

  // const getPhoneNumber = useCallback(
  //   (e) => {
  //     console.log('e', e)
  //     const { encryptedData, errMsg, iv } = e.detail;
  //     if (errMsg.includes("getPhoneNumber:ok")) {
  //       login({ encryptedData, iv });
  //     }
  //   },
  //   [login]
  // );

  const handleGetUserInfo = useCallback(async (e) => {
    console.log('handleGetUserInfo', e);
    Toast.loading("");
    const { errMsg, code } = e.detail;
    if (errMsg.includes('ok')) {
      const res = await wechatLoginByCode({ code });
      Toast.hideLoading();
      if (res.success) {
        Taro.navigateBack();
        setTimeout(() => {
          wechatLogin(res.data);
        }, 200);
      } else {
        // 失败的话，刷新下code
        Toast.error(res.message);
        // getCode();
      }
    } else {
      Toast.error(errMsg);
    }
  }, [])

  const handleCheckLicense = useCallback(() => {
    if (!isSelectLicense) {
      Toast.info(i18n.t("CHECK_LICENSE_TIPS"));
    }
  }, [isSelectLicense]);

  const buttonProps = useMemo(
    () =>
      isSelectLicense
        ? {
          onClick: login,
          openType: 'getUserInfo|agreePrivacyAuthorization',
          onAgreePrivacyAuthorization: bindAgreePrivacyAuthorization,
          // onGetUserinfo: login
        }
        : { onClick: handleCheckLicense },
    [isSelectLicense, login, handleCheckLicense, bindAgreePrivacyAuthorization]
  );
  return (
    <PageContainer
      title={i18n.t("LOGIN")}
      back={false}
      style={{ backgroundColor: "#fff" }}
    >
      <View
        style={{
          height: "70%",
          display: "flex",
          flexDirection: "column",
          justifyContent: "space-between",
          paddingTop: 94,
        }}
      >
        <View
          className="centerFlex"
          style={{ width: "100%", flexDirection: "column" }}
        >
          {appInfo.icon && <Image src={appInfo.icon} style={styles.icon} />}
          {appInfo.name && <Text style={styles.title}>{appInfo.name}</Text>}
        </View>
        <Button
          {...buttonProps}
          id={agreeButtonId}
          style={styles.button}
          className="centerFlex"
        >
          {/* <Image
            src={wechatIcon}
            style={{ width: 25, height: 25, marginRight: 20 }}
          /> */}
          <Text>{i18n.t("WECHAT_LOGIN")}</Text>
        </Button>
      </View>

      <View style={styles.licenseWrap}>
        {/* <Text style={{ color: "#797979", fontSize: 12, marginTop: 15 }}>
          手机用户请选择“已有账号登录”
        </Text> */}
        <View style={styles.license}>
          <View style={{ padding: 20, paddingRight: 8 }} onClick={() => setIsSelectLicense(!isSelectLicense)}>
            <CheckBox
              checked={isSelectLicense}
              style={styles.checkbox}
            />
          </View>
          <View style={{ display: "flex" }}>
            {i18n.t("I_AGREE")}
            <View style={styles.link} onClick={goLicense("private")}>
              {i18n.t("PRIVATE_DEAL")}、
            </View>
            <View style={styles.link} onClick={goLicense("agreement")}>
              {i18n.t("USER_SERVICE_DEAL")}
            </View>
          </View>
        </View>
      </View>
    </PageContainer>
  );
};

export default observer(NewLogin);
